import { ApiResponse, User, Portfolio, Recommendation, Transaction } from '../types';
import { customerService } from '../services/customerService';

const MOCK_DELAY = 800; // 模拟网络延迟

// 模拟API延迟
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

// 用户相关API
// 获取当前登录的管理员ID
const getCurrentManagerId = (): string => {
  try {
    const managerInfo = localStorage.getItem('currentManager');
    if (managerInfo) {
      const manager = JSON.parse(managerInfo);
      return manager.id;
    }
    return 'b_admin001'; // 默认值，用于兼容
  } catch (error) {
    console.error('Failed to get current manager ID:', error);
    return 'b_admin001'; // 默认值
  }
};

export const userApi = {
  // GET /api/user/profile
  getCurrentUser: async (): Promise<ApiResponse<User>> => {
    await delay(MOCK_DELAY);
    try {
      const currentManagerId = getCurrentManagerId();
      const user = customerService.getCustomerById(currentManagerId);
      if (!user) throw new Error('User not found');
      return { success: true, data: user as unknown as User };
    } catch (error) {
      return { success: false, error: '获取用户信息失败' };
    }
  },

  // PUT /api/user/profile
  updateProfile: async (userData: Partial<User>): Promise<ApiResponse<User>> => {
    await delay(MOCK_DELAY);
    try {
      const currentManagerId = getCurrentManagerId();
      const currentUser = customerService.getCustomerById(currentManagerId);
      if (!currentUser) throw new Error('User not found');
      const updatedUser = { ...currentUser, ...userData };
      return { success: true, data: updatedUser as unknown as User };
    } catch (error) {
      return { success: false, error: '更新用户信息失败' };
    }
  }
};

// 投资组合相关API
export const portfolioApi = {
  // GET /api/portfolios
  getPortfolios: async (_userId: string): Promise<ApiResponse<Portfolio[]>> => {
    await delay(MOCK_DELAY);
    try {
      // const portfolios = getPortfoliosByUserId(userId);
      const portfolios: Portfolio[] = []; // 临时返回空数组
      return { success: true, data: portfolios };
    } catch (error) {
      return { success: false, error: '获取投资组合失败' };
    }
  },

  // GET /api/portfolios/:id
  getPortfolio: async (_portfolioId: string): Promise<ApiResponse<Portfolio>> => {
    await delay(MOCK_DELAY);
    try {
      // const portfolio = mockPortfolios.find(p => p.id === portfolioId);
      const portfolio = null; // 临时返回null
      if (!portfolio) {
        return { success: false, error: '投资组合不存在' };
      }
      return { success: true, data: portfolio };
    } catch (error) {
      return { success: false, error: '获取投资组合详情失败' };
    }
  },

  // POST /api/portfolios
  createPortfolio: async (portfolioData: Omit<Portfolio, 'id' | 'createdAt' | 'updatedAt'>): Promise<ApiResponse<Portfolio>> => {
    await delay(MOCK_DELAY);
    try {
      const newPortfolio: Portfolio = {
        ...portfolioData,
        id: `portfolio_${Date.now()}`,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      };
      return { success: true, data: newPortfolio };
    } catch (error) {
      return { success: false, error: '创建投资组合失败' };
    }
  }
};

// AI推荐相关API
export const recommendationApi = {
  // GET /api/recommendations
  getRecommendations: async (_userId: string, filters?: { type?: string, riskLevel?: string }): Promise<ApiResponse<Recommendation[]>> => {
    await delay(MOCK_DELAY);
    try {
      // let recommendations = [...mockRecommendations];
      let recommendations: Recommendation[] = []; // 临时返回空数组

      if (filters?.type) {
        recommendations = recommendations.filter(r => r.type === filters.type);
      }
      if (filters?.riskLevel) {
        recommendations = recommendations.filter(r => r.riskLevel === filters.riskLevel);
      }

      return { success: true, data: recommendations };
    } catch (error) {
      return { success: false, error: '获取AI推荐失败' };
    }
  },

  // GET /api/recommendations/high-confidence
  getHighConfidenceRecommendations: async (): Promise<ApiResponse<Recommendation[]>> => {
    await delay(MOCK_DELAY);
    try {
      // const recommendations = getHighConfidenceRecommendations();
      const recommendations: Recommendation[] = []; // 临时返回空数组
      return { success: true, data: recommendations };
    } catch (error) {
      return { success: false, error: '获取高置信度推荐失败' };
    }
  },

  // POST /api/recommendations/:id/execute
  executeRecommendation: async (_recommendationId: string, _params: any): Promise<ApiResponse<Transaction>> => {
    await delay(MOCK_DELAY);
    try {
      // 临时直接返回失败，因为没有可用的推荐数据
      return { success: false, error: '推荐功能暂不可用' };
    } catch (error) {
      return { success: false, error: '执行推荐失败' };
    }
  }
};


// 聊天和AI助手相关API (为未来扩展预留)
export const chatApi = {
  // GET /api/conversations
  getConversations: async (_userId: string): Promise<ApiResponse<any[]>> => {
    await delay(MOCK_DELAY);
    return { success: true, data: [] }; // 暂时返回空数组
  },

  // POST /api/conversations/:id/messages
  sendMessage: async (_conversationId: string, _message: string): Promise<ApiResponse<any>> => {
    await delay(MOCK_DELAY);
    return { success: true, data: { id: Date.now(), message: _message, timestamp: new Date().toISOString() } };
  },

  // GET /api/ai/suggestions
  getAiSuggestions: async (_context: any): Promise<ApiResponse<string[]>> => {
    await delay(MOCK_DELAY);
    const suggestions = [
      '基于当前市场情况，建议考虑增加科技股比重',
      '您的投资组合风险偏低，可以适当提高预期收益',
      '建议关注即将发布财报的优质成长股'
    ];
    return { success: true, data: suggestions };
  }
};

// 策略库相关API
const STRATEGY_API_BASE = '/langchain-backend/invest/strategies';

export const strategyApi = {
  // 获取策略列表
  getStrategies: async (params?: { category?: string; search?: string; created_by?: string }) => {
    try {
      const query = params ? '?' + new URLSearchParams(params as any).toString() : '';
      const res = await fetch(`${STRATEGY_API_BASE}${query}`, {
        method: 'GET',
        headers: { 'Accept': 'application/json' },
      });

      if (!res.ok) {
        throw new Error(`HTTP error! status: ${res.status}`);
      }

      const data = await res.json();
      return data;
    } catch (error) {
      console.error('获取策略列表失败:', error);
      return { success: false, error: error instanceof Error ? error.message : '获取策略列表失败' };
    }
  },
  // 新增策略
  createStrategy: async (data: any) => {
    try {
      const res = await fetch(`${STRATEGY_API_BASE}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data),
      });

      if (!res.ok) {
        throw new Error(`HTTP error! status: ${res.status}`);
      }

      const responseData = await res.json();
      return responseData;
    } catch (error) {
      console.error('创建策略失败:', error);
      return { success: false, error: error instanceof Error ? error.message : '创建策略失败' };
    }
  },
  // 更新策略
  updateStrategy: async (id: number, data: any) => {
    try {
      const res = await fetch(`${STRATEGY_API_BASE}/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data),
      });

      if (!res.ok) {
        throw new Error(`HTTP error! status: ${res.status}`);
      }

      const responseData = await res.json();
      return responseData;
    } catch (error) {
      console.error('更新策略失败:', error);
      return { success: false, error: error instanceof Error ? error.message : '更新策略失败' };
    }
  },
  // 删除策略
  deleteStrategy: async (id: number) => {
    try {
      const res = await fetch(`${STRATEGY_API_BASE}/${id}`, {
        method: 'DELETE',
        headers: { 'Accept': 'application/json' },
      });

      if (!res.ok) {
        throw new Error(`HTTP error! status: ${res.status}`);
      }

      const responseData = await res.json();
      return responseData;
    } catch (error) {
      console.error('删除策略失败:', error);
      return { success: false, error: error instanceof Error ? error.message : '删除策略失败' };
    }
  },
  // 获取单个策略
  getStrategyById: async (id: number) => {
    try {
      const res = await fetch(`${STRATEGY_API_BASE}/${id}`, {
        method: 'GET',
        headers: { 'Accept': 'application/json' },
      });

      if (!res.ok) {
        throw new Error(`HTTP error! status: ${res.status}`);
      }

      const data = await res.json();
      return data;
    } catch (error) {
      console.error('获取策略详情失败:', error);
      return { success: false, error: error instanceof Error ? error.message : '获取策略详情失败' };
    }
  },
};

// 高潜客户相关API
const CUSTOMER_API_BASE = '/langchain-backend/customer/kyc_profiles';

export const customerApi = {
  // 获取KYC高潜客户列表
  getKycProfiles: async (params?: { page?: number; page_size?: number; use_pagination?: boolean }) => {
    try {
      const query = params ? '?' + new URLSearchParams(params as any).toString() : '';
      const res = await fetch(`${CUSTOMER_API_BASE}${query}`, {
        method: 'GET',
        headers: { 'accept': 'application/json' }
      });
      const data = await res.json();
      return data;
    } catch (e) {
      return { success: false, message: '获取高潜客户失败', data: null };
    }
  }
};

// 更新客户手动选择的投资策略
export const updateCustomerOverrideStrategy = async (userName: string, overrideStrategyId: number | null) => {
  try {
    const res = await fetch(`${CUSTOMER_API_BASE}/${userName}`, {
      method: 'PUT',
      headers: {
        'accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ override_investment_strategy: overrideStrategyId }),
    });
    return await res.json();
  } catch (error) {
    return { success: false, message: '更新策略覆盖设置失败' };
  }
};
